/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managers;

import entities.Article;
import entities.UserProject;
import interfaces.UserProjectInterface;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Implementation of UserProjectInterface
 *
 * @author Thibault
 */
@Stateless
public class UserProjectManager implements UserProjectInterface {

    @PersistenceContext(unitName = "project")
    private EntityManager em;

    @Override
    public void createUserProject(UserProject userProject) {
        em.persist(userProject);
    }

    @Override
    public void removeUser(long id) throws EJBException {
        em.remove(em.find(UserProject.class, id));
    }

    @Override
    public UserProject findById(long id) throws EJBException {
        UserProject up = em.find(UserProject.class, id);
        if (up != null) {
            return up;
        } else {
            throw (new EJBException("No UserProject entity found for id " + id));
        }
    }

    @Override
    public UserProject findUserByLoginAndPassword(String login, String password) {
        Query query =
                em.createNamedQuery("UserProject.findByLoginAndPassword");
        query.setParameter("login", login);
        query.setParameter("password", password);
        try {
            return (UserProject) query.getSingleResult();
        } catch (NoResultException nre) {
            throw (new EJBException("No UserProject entity found for login " + login + " password " + password));
        }
    }

    @Override
    public void updateUser(UserProject user) {
        em.merge(user);
    }

    @Override
    public boolean isMailAlreadyUsed(String mail) {
        Query query =
                em.createNamedQuery("UserProject.isMailAlreadyUsed");
        query.setParameter("mail", mail);
        try {
            query.getSingleResult();
            return true;
        } catch (NoResultException nre) {
            return false;
        }
    }

    @Override
    public List<Article> getListAriticleWithBidForUser(long idUser) {
        Query query =
                em.createNamedQuery("UserProject.getListAriticleWithBidForUser");
        query.setParameter("id", idUser);
        System.out.println("getListAriticleWithBidForUser : ICIIIIIIIII");
        return (List<Article>) query.getResultList();
    }
}
